//
//  FileUtils.m
//  dice
//
//  Created by zzb on 13-5-19.
//  Copyright (c) 2013年 BlueStorm. All rights reserved.
//

#import <sys/stat.h>
#import "FileUtil.h"
#import "StringUtil.h"

@implementation FileUtil

+ (BOOL)isDir:(NSString *)file
{
    //NSFileManager *fileManager = [NSFileManager defaultManager];
    return YES;
}

/**
 * 判断路径是否存在
 */
+ (BOOL)isPathExist:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:path];
}

+ (BOOL)createDir:(NSString *)dirPath {
    
    if (dirPath == nil) {
        return NO;
    }
    
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error] != YES) {
        int errCode = (error!=nil ? (int)error.code : -1);
        NSLog(@"Create dir error: [error code:%d], [file:%@]", errCode, dirPath);
        
        return NO;
    }
    
    return YES;
}

+ (void)removeDir:(NSString *)dirPath
{
    [FileUtil removeDir:dirPath needSelfDir:YES];
}

+ (void)removeSubDir:(NSString *)dirPath
{
    [FileUtil removeDir:dirPath needSelfDir:NO];
}

+ (void)removeDir:(NSString *)dirPath needSelfDir:(BOOL)needSelfDir
{
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSLog(@"Removing dir: %@", dirPath);
    
    for (NSString *file in [fileManager contentsOfDirectoryAtPath:dirPath error:nil]) {
        NSString *filePath = [dirPath stringByAppendingPathComponent:file];
        NSLog(@"Removing file : %@", filePath);
        
        if ([fileManager removeItemAtPath:filePath error:&error] != YES) {
            int errCode = (error!=nil ? (int)error.code : -1);
            NSLog(@"Removing file error: [error code:%d], [file:%@]", errCode, filePath);
        }
    }
    
    if (needSelfDir) {
        [FileUtil removeFile:dirPath];
    }
}

+ (void)removeFile:(NSString *)filePath {
    
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager removeItemAtPath:filePath error: &error] != YES) {
        int errCode = (error!=nil ? (int)error.code : -1);
        NSLog(@"Remove file error: [error code:%d], [file:%@]", errCode, filePath);
    }
}

+ (BOOL)copyDirFrom:(NSString *)fromDir to:(NSString *)toDir
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
	if ([fileManager fileExistsAtPath:toDir]) {
        return NO;
    }
	
    NSError *error = nil;
	[fileManager copyItemAtPath:fromDir toPath:toDir error:&error];
    if (error) {
        return NO;
    }
    
    return YES;
}

+ (void)writeFile:(NSString *)filePath withString:(NSString *)string withEncoding:(NSStringEncoding)encoding
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    [fileManager createFileAtPath:filePath contents:[string dataUsingEncoding:encoding] attributes:nil];
    
//    NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
//    
////    [file seekToEndOfFile];
//    [file writeData:[string dataUsingEncoding:encoding]];
//    [file closeFile];
}

/**
 * 获取文件的创建时间
 */
+ (NSDate *)creationDateForFile:(NSString *)filePath {
    
    const char *filename = [filePath UTF8String];
    
    struct stat filestat;
    if (stat(filename, &filestat) != 0) {
        NSLog(@"Get file stat errno: %d", errno);
        return nil;
    }
    
    struct timespec createTime = filestat.st_mtimespec;
    
    return  [NSDate dateWithTimeIntervalSince1970:createTime.tv_sec];
    
    //    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    NSDictionary *attr = [fileManager attributesOfFileSystemForPath:filePath error:nil];
    //    if (attr) {
    //        return [attr valueForKey:NSFileCreationDate];
    //    }
    //
    //    return nil;
}


+ (float)sizeForFile:(NSString *)filePath {
    
    const char *filename = [filePath UTF8String];
    
    struct stat filestat;
    if (stat(filename, &filestat) != 0) {
        NSLog(@"Get file stat errno: %d", errno);
        return 0;
    }
    
    return filestat.st_size;
}

+ (float)sizeForDir:(NSString *)dirPath
{
    if ([StringUtil isEmpty:dirPath]) {
        return 0;
    }
    
    float size = 0;
    
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSArray *files = [fileManager contentsOfDirectoryAtPath:dirPath error:&error];
    for (int i=0; i<files.count; i++) {
        
        NSString *fullPath = [dirPath stringByAppendingPathComponent:files[i]];
        
        BOOL isDir;
        if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDir]) {
            if (isDir) {
                size += [FileUtil sizeForDir:fullPath];
            }
            else {
                size += [FileUtil sizeForFile:fullPath];
            }
        }
    }
    
    return size;
}

+ (NSString *)displayNameAtPath:(NSString *)path {
    NSFileManager * fileManager = [NSFileManager defaultManager];
    //通过文件管理器来获得文件名
    
    return [fileManager displayNameAtPath:path];
}


///处理文件大小，显示为容易理解的字符串形式
+ (NSString *)getFileStringSize:(long)size
{
    double format_size = size;
    
    if(format_size < 1024){
        return [NSString stringWithFormat:@"%.2f B", format_size];
    }
    
    format_size = format_size / 1024;
    
    if(format_size < 1024){
        return [NSString stringWithFormat:@"%.2f K", format_size];
    }
    
    
    format_size = format_size / 1024;
    
    if(format_size < 1024){
        return [NSString stringWithFormat:@"%.2f M", format_size];
    }
    
    
    format_size = format_size / 1024;
    
    return [NSString stringWithFormat:@"%.2f G", format_size];
}


@end
